package com.dmj.sqldsl.builder;

import static java.util.stream.Collectors.toList;

import com.dmj.sqldsl.builder.column.ColumnBuilder;
import com.dmj.sqldsl.builder.column.type.ColumnLambda;
import com.dmj.sqldsl.builder.config.EntityConfig;
import com.dmj.sqldsl.builder.config.GlobalConfig;
import com.dmj.sqldsl.model.DslInsert;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class InsertValuesBuilder<T> {

  private final InsertBuilder<T> insertBuilder;

  private final Collection<T> values;

  @SafeVarargs
  public final <R> InsertConflictBuilder<T, R> conflict(ColumnLambda<T, R>... columnLambdas) {
    List<ColumnBuilder<T, R>> columnBuilders = Arrays.stream(columnLambdas)
        .map(ColumnLambda::getColumnBuilder).collect(toList());
    return new InsertConflictBuilder<>(this, columnBuilders);
  }

  @SafeVarargs
  public final <R> InsertReturningBuilder<T, R> returning(ColumnLambda<T, R>... columnLambdas) {
    List<ColumnBuilder<T, R>> columnBuilders = Arrays.stream(columnLambdas)
        .map(ColumnLambda::getColumnBuilder).collect(toList());
    return new InsertReturningBuilder<>(this, columnBuilders);
  }


  protected DslInsert toInsert(EntityConfig config) {
    return DslInsert.builder()
        .table(insertBuilder.getEntityBuilder().buildTable(config))
        .entities(values.stream().map(config::getTableEntity).collect(Collectors.toList()))
        .build();
  }

  public DslInsert toInsert() {
    return this.toInsert(GlobalConfig.getEntityConfig());
  }
}
